package com.qingzhuge.manager.security.handler;

import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhuge.common.HttpCode;
import com.qingzhuge.dto.response.ResponseBodyDto;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * @author zeroxiao
 * @date 2019/9/10 20:37
 * 客户端异常处理
 * 1. 可以根据 AuthenticationException 不同细化异常处理
 */
@Slf4j
@Component
@AllArgsConstructor
public class ResourceAuthUnauthorizedHandler implements AuthenticationEntryPoint , Serializable {
    private static final long serialVersionUID = -4991696622780310597L;
    private final ObjectMapper objectMapper;

    /**
     * 当用户尝试访问安全的REST资源而不提供任何凭据时，将调用此方法发送401 响应
     */
    @Override
    @SneakyThrows
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) {
        response.setCharacterEncoding("UTF8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        ResponseBodyDto<String> result = new ResponseBodyDto<>();
        result.setCode(HttpCode.FORBIDDEN.value());
        result.setMessage(HttpCode.FORBIDDEN.message());
        response.setStatus(HttpStatus.HTTP_OK);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
        log.debug("没有任何凭据");
    }
}